package org.brownflat.dbinit.mysql;

import org.brownflat.dbinit.upgrade.Upgrade;
import org.brownflat.dbinit.upgrade.UpgradeSource;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>Database Init &copy Rupert Jones 2013</p>
 *
 * @author rup
 */
public class MySQLUpgradeSource implements UpgradeSource {
    private UpgradeSource source;

    public MySQLUpgradeSource(UpgradeSource source) {
        this.source = source;
    }

    @Override
    public List<Upgrade> getUpgrades() {
        List<Upgrade> upgrades = source.getUpgrades();
        checkForDuplicateVersions(upgrades);
        return upgrades;
    }

    private void checkForDuplicateVersions(List<? extends Upgrade> upgrades) {
        Map<Integer, Upgrade> validatingMap = new HashMap<Integer, Upgrade>();
        for(Upgrade upgrade : upgrades) {
            if(validatingMap.containsKey(upgrade.getSequence())) {
                throw new RuntimeException("Found duplicate patch sequence number: " + upgrade.getSequence());
            }
            validatingMap.put(upgrade.getSequence(), upgrade);
        }
    }

    @Override
    public List<Upgrade> getUpgradesFrom(int sequence) {
        List<Upgrade> upgrades = source.getUpgradesFrom(sequence);
        checkForDuplicateVersions(upgrades);
        return upgrades;
    }

    @Override
    public void setInitialUpgrade(Upgrade initial) {
        this.source.setInitialUpgrade(initial);
    }
}
